package com.shadow.bus.main;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.shadow.bus.config.NetState;
import com.shadow.bus.config.ServiceUrl;
import com.shadow.bus.config.SpKey;
import com.shadow.bus.config.WorkStatusCode;
import com.shadow.bus.entity.BusInfoEntity;
import com.shadow.bus.entity.BusTypeEntity;
import com.shadow.bus.entity.StartWorkEvent;
import com.shadow.bus.event.RefreshMainEvent;
import com.shadow.bus.event.StartBrotherEvent;
import com.shadow.bus.main.setting.SettingDelegate;
import com.shadow.bus.main.work.WorkDelegate;
import com.zhangyu.shadow.core.delegate.RxShadowDelegate;
import com.zhangyu.shadow.core.net.callback.IError;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.net.rx.RxRestClient;
import com.zhangyu.shadow.core.util.storage.ShadowPreference;
import com.zhangyu.shadow.core.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import busfix.tepth.com.shadow_bus.R;
import busfix.tepth.com.shadow_bus.R2;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zhangyu
 * @date 2018/7/2
 */

public class MainDelegate extends RxShadowDelegate {
    public static MainDelegate newInstance() {
        Bundle args = new Bundle();
        MainDelegate fragment = new MainDelegate();
        fragment.setArguments(args);
        return fragment;
    }

    @BindView(R2.id.toolbar_search)
    Toolbar mToolbar;
    @BindView(R2.id.et_search)
    EditText mEtSearch;
    @BindView(R2.id.tv_refresh)
    TextView mTvEmpty;
    @BindView(R2.id.viewpager)
    ViewPager mViewPager;
    @BindView(R2.id.tabs)
    TabLayout mTabLayout;
    private MainPagerAdapter mPagerAdapter;
    private List<Fragment> mDelegates = new ArrayList<>();
    private List<BusTypeEntity> mAllData = new ArrayList<>();
    private boolean isRefreshing = false;

    @Override
    public Object setLayout() {
        return R.layout.delegate_main;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        EventBus.getDefault().register(this);
        mToolbar.inflateMenu(R.menu.setting);
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int i = item.getItemId();
                if (i == R.id.menu_search) {
                    search(mEtSearch.getText().toString().trim());
                } else if (i == R.id.menu_setting) {
                    start(SettingDelegate.newInstance());
                }
                return true;
            }
        });
        mEtSearch.setHint("请输入车辆的编号");
        mEtSearch.setInputType(InputType.TYPE_CLASS_NUMBER);
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search(mEtSearch.getText().toString().trim());
                    return true;
                }
                return false;
            }
        });
        mPagerAdapter = new MainPagerAdapter(getChildFragmentManager(), mDelegates);
        mViewPager.setAdapter(mPagerAdapter);

    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        onRefresh(null);
    }

    private void search(String key) {
        try {
            if (mAllData != null) {
                ArrayList<BusTypeEntity> list = new ArrayList<>();
                for (BusTypeEntity type : mAllData) {
                    BusTypeEntity bustype = new BusTypeEntity();
                    bustype.setWorkStatus(type.getWorkStatus());
                    bustype.setWorkStatusCode(type.getWorkStatusCode());
                    List<BusInfoEntity> busInfos = type.getListRepair();
                    ArrayList<BusInfoEntity> bs = new ArrayList<>();
                    for (BusInfoEntity busInfo : busInfos) {
                        if (busInfo.getVehicleCode().contains(key)) {
                            bs.add(busInfo);
                        }
                    }
                    bustype.setListRepair(bs);
                    list.add(bustype);
                }
                initData(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void requestData() {
        if (!NetState.IS_NET_CONNECT) {
            showInfo("没有网络，请检查网络！或者刷新试试");
        } else {
            isRefreshing = true;
            mDisposables.add(RxRestClient.builder()
                    .url(ServiceUrl.BUS_TYPE)
                    .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                    .success(new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            showInfo("请求成功,正在加载界面数据!");
                            new MainDataConverter()
                                    .converter(response, new MainDataConverter.OnConverterListener() {
                                        @Override
                                        public void onConverter(ArrayList<BusTypeEntity> list) {
                                            try {
                                                if (list == null || list.isEmpty()) {
                                                    showInfo("没有数据，刷新试试!");
                                                } else {
                                                    mAllData.clear();
                                                    mAllData.addAll(list);
                                                    initData(list);
                                                    showData();
                                                }
                                                isRefreshing = false;
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }

                                        }
                                    });

                        }
                    })
                    .error(new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            showInfo((msg == null || msg.isEmpty()) ? "请求超时了!刷新试试!" : msg);
                            isRefreshing = false;
                        }
                    })
                    .build()
                    .get());
        }
    }

    private void initData(ArrayList<BusTypeEntity> list) throws Exception {
        Log.e("initData", "start");
        mViewPager.setOffscreenPageLimit(list.size());
        mDelegates.clear();
        List<View> tabViews = new ArrayList<>();
        for (BusTypeEntity entity : list) {
            ArrayList<BusInfoEntity> infoEntities = entity.getListRepair();
            mDelegates.add(TabFragment.newInstance(infoEntities));
            View v = LayoutInflater.from(getContext()).inflate(R.layout.view_tab_title, null);
            TextView textView = v.findViewById(R.id.tv_title);
            String size = infoEntities == null ? "0" : infoEntities.size() + "";
            int index[] = new int[1];
            String str = WorkStatusCode.getNameMap().get(entity.getWorkStatusCode())
                    + "(" + size + ")";
            index[0] = str.indexOf(size);
            SpannableStringBuilder style = new SpannableStringBuilder(str);
            int color = 0;
            switch (entity.getWorkStatusCode()) {
                case WorkStatusCode.UNDER_PLAN:
                    color = getContext().getResources().getColor(R.color.bus_under_plan);
                    break;
                case WorkStatusCode.FINISH_PLAN:
                case WorkStatusCode.READY_WORK:
                    color = getContext().getResources().getColor(R.color.bus_finish_plan);
                    break;
                case WorkStatusCode.UNDER_WORK:
                    color = getContext().getResources().getColor(R.color.bus_under_work);
                    break;
                case WorkStatusCode.FINISH_WORK:
                    color = getContext().getResources().getColor(R.color.bus_finish_work);
                    break;
                case WorkStatusCode.COMPLETE_WORK:
                    color = getContext().getResources().getColor(R.color.bus_complete_work);
                    break;
            }
            style.setSpan(new ForegroundColorSpan(color), index[0], index[0] + size.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            textView.setText(style);
            tabViews.add(v);
        }
        mPagerAdapter.notifyDataSetChanged();
        mTabLayout.setupWithViewPager(mViewPager);
        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(tabViews.get(i));
            }
        }
        Log.e("initData", "end");
    }

    private void showInfo(String info) {
        try {
            mTvEmpty.setVisibility(View.VISIBLE);
            mViewPager.setVisibility(View.GONE);
            mTabLayout.setVisibility(View.GONE);
            mTvEmpty.setText(info);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void showData() {
        try {
            mTvEmpty.setVisibility(View.GONE);
            mViewPager.setVisibility(View.VISIBLE);
            mTabLayout.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Subscribe
    public void onRefresh(RefreshMainEvent event) {

        Log.e("onRefresh", "onRefresh");
        showInfo("正在加载，请稍候...");
        requestData();
    }

    @Subscribe
    public void onStartWork(StartWorkEvent event) {
        start(WorkDelegate.newInstance(event.code, event.id));
    }

    @Subscribe
    public void onSatartBrother(StartBrotherEvent event) {
        start(event.mShadowDelegate);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R2.id.btn_reset)
    public void onRefreshClick() {
        if (isRefreshing) {
            ToastUtils.showToast(getContext(), "别点太快了,休息一下..");
            return;
        }
        showInfo("正在刷新，请稍候");
        requestData();
    }
}
